#include<stdio.h>
#include<stdlib.h>

typedef struct CLNode{
	int data;
	struct CLNode *next;
}CLNode;

int initiate(CLNode **list){
	if((*list = (CLNode*) malloc(sizeof(CLNode))) == NULL){
		printf("space malloc failed");
		return 0;
	}

	(*list)->data = 0;
	(*list)->next = (*list);
	return 1;
}

int insert(CLNode *head, int i, int data){
	if(i < 0){
		printf("illegal position to insert\n");
		return 0;
	}

	int count = 0;
	CLNode *p, *new;
	p = head;
	++count;

	while(count != i && p->next != head){ 
		p = p->next;
		++count;
	}

	if(count != i && p->next == head && i != 0){
		printf("illegal position to insert\n");
		return 0;
	}

	if((new = (CLNode*) malloc(sizeof(CLNode))) == NULL){
		printf("space malloc failed");
		return 0;
	}
	new->data = data;
	new->next = p->next;
	p->next = new;
	return 1;
}

int print(CLNode *head){
	CLNode *p =head;
	p = p->next;
	while(p != head){
		printf("%d ", p->data);
		p = p->next;
	}
	return 1;
}

int generate(CLNode *head){
	int data;
	do{
		printf("Enter the data of the list(0 to stop):");
		scanf("%d", &data);
		if(data == 0)
			break;
		if(!insert(head, 0, data)){
			printf("insert failed\n");
			return 0;
		}
	}while(data != 0);

	return 1;
}

int main(){
	CLNode *head, **list;
	list = &head;
	if(!initiate(list)){
		printf("initiate failed\n");
		return 0;
	}

	if(!generate(head)){
		printf("generate failed\n");
		return 0;
	}

	print(head);
}
